/**
 * Created by zhanglihe on 15/11/10.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'template',
    'model',
    'dialog',
    'ckeditor'
], function ($, common, ready, template, Model, dialog, ckeditor) {

    var index = function () {
        this.init();
    };

    index.prototype = {
        init: function () {
            var _this = this;
            //商品属性
            $.ajax({
                url: _global.url.api + 'goods_attrs',
                data: {limit: 1000},
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        var goods_attrs = {};
                        $.each(res.data, function () {
                            goods_attrs[this.id] = this;
                        });
                        _this.set('goods_attrs', goods_attrs);
                    }
                }
            });
            //分类
            $.ajax({
                url: _global.url.api + 'site_categorys',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('category', res.data);
                    }
                }
            });
            //运费模板
            $.ajax({
                url: _global.url.api + 'shipping',
                type: 'get',
                async: false,
                success: function (res) {
                    if (res.code == 0) {
                        _this.set('shipping', res.data);
                    }
                }
            });

            _this.set('defaultFree', 0);

            //行邮税类目
            if (_global.site_info.is_oversea == 1) {
                $.ajax({
                    url: _global.url.api + 'oversea_catalogs',
                    type: 'get',
                    async: false,
                    success: function (res) {
                        if (res.code == 0) {
                            _this.set('catalogs', res.data);
                        }
                    }
                });
            }
            this.goodsSkuInit();
            this.albumInit();
            this.fetch();
            this.event();
            _this.spec_key = [];
        },
        fetch: function () {
            var _this = this;

            $('#main-view').html(template('add-tpl', {
                shipping: this.shipping,
                is_oversea: _global.site_info.is_oversea, catalogs: this.catalogs
            }));

            this.model = new Model({
                url: _global.url.api + 'goods',
                data: {},
                valid_config: {
                    name: 'required',
                    cate_ids: 'required',
                    //sn: 'required',
                    //weight:'number',
                    //rebate:'number',
                    //rebate1:'number',
                    //rebate2:'number',
                    //price: 'price',
                    market_price: function (model, val) {
                        return parseFloat(val) >= parseFloat(model.get_data('price'));
                    },
                    shipping_template: 'number',
                    details: 'required',
                    stock: function (model, val) {
                        return parseInt(val) >= 0
                    },
                    album: 'required'
                },

                /**
                 * edit by hp
                 */
                success: function () {
                    _this.callback('/site/goods');
                }

            });

        },
        /**
         * edit by hp
         * @param uri
         */
        callback: function (uri) {
            if (uri) {
                window.location.href = uri;
            }
        },

        set: function ($k, $v) {
            this[$k] = $v;
        },
        event: function () {
            var _this = this;

            $('body').on('click', '[name="_is_free_shipping_"]', function() {
                var isFree = $(this).val();

                $('#shipping_template').empty();
                $('#shipping_template').append('<option value="">--请选择--</option>');
                $('#shipping_template option').each(function(index, value) {
                    var optionSid = $(value).attr('s-id');
                    for (var i = 0; i < _this.shipping.length; i++) {
                        var f = _this.shipping[i];
                        if (isFree == 1) {
                            if (!f.site_id || f.is_free == 1) {
                                $('#shipping_template').append('<option s-id="'+ f.site_id+'" value="'+f.id+'">'+f.name+'</option>');
                            }
                        } else {
                            if (f.site_id > 0 && f.is_free == 0) {
                                $('#shipping_template').append('<option s-id="'+ f.site_id+'" value="'+f.id+'">'+f.name+'</option>');
                            }
                        }
                    }
                });
            });

            $('input,select,textarea').on('change', function (e) {
                _this.change(e);
            });

            //保存事件
            var group_discount;
            $.ajax({
                url: _global.url.api + 'site_group_discount',
                data: {site_id: _global.site_info.id},
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    group_discount = res;
                    console.log(group_discount);
                }
            });
            $('#btn-save').on('click', function (e) {
                e.preventDefault();
                //点击时判断是否设置两人拼团价
                var group_price = $("#group_price").val();
                console.log(1111111111111);
                console.log(group_discount);
                if (group_price < 0 && group_discount == 0) {
                    var cate_ids = new Array();
                    $('#cate-name').children().each(function () {
                        cate_ids.push($(this).attr('id'));
                    });
                    $.ajax({
                        url: _global.url.api + 'not_group_two_cate',
                        data: {cate_ids: cate_ids},
                        type: 'put',
                        success: function (res) {
                            if (res == 0) {
                                dialog({
                                    title: '请设置2人拼团价',
                                    content: template('group-two-tpl'),
                                    width: 500,
                                    ok: function () {
                                        var data = {};
                                        data.group_price = $('#group-price-tpl').val();
                                        data.group_discount = $('#group-discount-tpl').val();
                                        data.goods_id = 0;
                                        console.log(data);
                                        if (new Model({
                                                url: _global.url.api + 'group_two',
                                                data: data
                                            }).put()) {
                                        }
                                        var group_price = parseFloat(data.group_price);
                                        $("#group_price").val(group_price.toFixed(2));
                                    }, cancel: function () {
                                    }
                                }).show();
                            } else {
                                //属性
                                _this.model.data.goods_attr_ids = _this.getAttrId();
                                _this.model.data.details = $('[name="details"]').val();
                                _this.model.data.intro = $('[name="intro"]').val();
                                //goods_sku
                                if (!_this.goodsSku.validation()) {
                                    Alert({"msg":"商品属性验证失败", "type":"error"});
                                    return false;
                                }
                                //是否跨境购
                                _this.model.data.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                                //分享家提成比例
                                _this.model.data.rebate = $('input[name="rebate"]').val();
                                //是否单品包邮
                                _this.model.data._is_free_shipping_ = $('input[name="_is_free_shipping_"]:checked').val();
                                _this.model.data._baoming = $('input[name="_baoming"]:checked').val();
                                _this.model.data._byself = $('input[name="_byself"]:checked').val();
                                _this.model.data.market_price = $("#market_price").val();
                                _this.model.data.price = $("#price").val();
                                _this.model.data.goods_unicoin = $("[name='goods_unicoin']").val();
                                _this.model.data.is_free_tax = $('input[name="is_free_tax"]').is(':checked') ? 1 : 0;
                                _this.model.data.maidian = $("[name='maidian']").val();
                                _this.model.data.tax_money = $("#tax_money").val();
                                _this.model.data.group_price = $("#group_price").val();
                                _this.model.data.video = $("#video").val();
                                _this.model.data.position = $("input[name='video']:checked").val();
                                if (Number(_this.model.data.market_price) < Number(_this.model.data.price)) {
                                    Alert({msg: '市场价要大于等于121价', type: 'error'});
                                    $("#market_price").val("");
                                    return false;
                                }
                                //商品规格参数
                                var spec = _this.getSpecification();
                                var maps = new Object();
                                for (var i = 0; i < spec.length; i++) {
                                    var lab = $('#spec' + spec[i]['name']).attr('id');

                                    if (typeof(lab) === 'undefined') {
                                        continue;
                                    }
                                    if (typeof(spec[i]['value']) === 'undefined' || spec[i]['value'].length == '0') {
                                        if (spec[i]['required'] == '1') {
                                            Alert({msg: spec[i]['title'] + '为必填项', type: 'error'});
                                            return false;
                                        } else {
                                            continue;
                                        }
                                    }
                                    maps[spec[i]['name']] = spec[i]['value'];
                                }
                                _this.model.data.specification = maps;
                                if (_this.model.post()) {
                                    _this.fetch();
                                }
                            }
                        }
                    });
                } else {
                    //属性
                    _this.model.data.goods_attr_ids = _this.getAttrId();
                    _this.model.data.details = $('[name="details"]').val();
                    _this.model.data.intro = $('[name="intro"]').val();
                    //goods_sku
                    if (!_this.goodsSku.validation()) {
                        Alert({"msg":"商品属性验证失败", "type":"error"});
                        return false;
                    }
                    //是否跨境购
                    _this.model.data.is_oversea = $('input[name="is_oversea"]').is(':checked') ? 1 : 0;
                    //分享家提成比例
                    _this.model.data.rebate = $('input[name="rebate"]').val();
                    //是否单品包邮
                    _this.model.data._is_free_shipping_ = $('input[name="_is_free_shipping_"]:checked').val();
                    _this.model.data._baoming = $('input[name="_baoming"]:checked').val();
                    _this.model.data._byself = $('input[name="_byself"]:checked').val();
                    _this.model.data.market_price = $("#market_price").val();
                    _this.model.data.price = $("#price").val();
                    _this.model.data.goods_unicoin = $("[name='goods_unicoin']").val();
                    _this.model.data.is_free_tax = $('input[name="is_free_tax"]').is(':checked') ? 1 : 0;
                    _this.model.data.maidian = $("[name='maidian']").val();
                    _this.model.data.tax_money = $("#tax_money").val();
                    _this.model.data.group_price = $("#group_price").val();
                    _this.model.data.video = $("#video").val();
                    _this.model.data.position = $("input[name='video']:checked").val();
                    if (Number(_this.model.data.market_price) < Number(_this.model.data.price)) {
                        Alert({msg: '市场价要大于等于121价', type: 'error'});
                        $("#market_price").val("");
                        return false;
                    }
                    //商品规格参数
                    var spec = _this.getSpecification();
                    var maps = new Object();
                    for (var i = 0; i < spec.length; i++) {
                        var lab = $('#spec' + spec[i]['name']).attr('id');

                        if (typeof(lab) === 'undefined') {
                            continue;
                        }
                        if (typeof(spec[i]['value']) === 'undefined' || spec[i]['value'].length == '0') {
                            if (spec[i]['required'] == '1') {
                                Alert({msg: spec[i]['title'] + '为必填项', type: 'error'});
                                return false;
                            } else {
                                continue;
                            }
                        }
                        maps[spec[i]['name']] = spec[i]['value'];
                    }
                    _this.model.data.specification = maps;
                    if (_this.model.post()) {
                        _this.fetch();
                    }
                }
            });
            $("#market_price").blur(function (e) {
                e.preventDefault();
                var price = $.trim($("#price").val());
                if (Number($.trim($(this).val())) < Number(price) && $.trim($(this).val()) != '') {
                    Alert({msg: '市场价要大于等于121价', type: 'error'});
                    $("#market_price").val("");
                    return false;
                }
            });

            //进口税
            $('[name="is_oversea"]').on('click', function () {
                if ($(this).is(':checked')) {
                    $('#form-catalog').slideDown();
                    $('.tax').show();

                    if ($('[name="is_free_tax"]').is(':checked')) {
                        $('#tax_money').show();
                    } else {
                        $('#tax_money').hide();
                    }
                } else {
                    $('#form-catalog').slideUp();
                    $('.tax').hide();
                }
            });
            //行邮税
            $('[name="is_free_tax"]').on('click', function () {
                if ($(this).is(':checked')) {
                    $('#tax_money').show();
                } else {
                    $('#tax_money').hide();
                }
            });

            $('[name="price"]').on('blur', function () {
                var goods_price = $(this).val();
                if (goods_price > 0) {
                    $.ajax({
                        url: _global.url.api + 'goods_group_price',
                        data: {goods_price: goods_price, site_id: _global.site_info.id},
                        type: 'get',
                        dataType: 'json',
                        success: function (res) {
                            if (res.data > 0) {
                                $('[name="group_price"]').val(res.data);
                            }
                        }
                    });
                }
            });

            $('select[name="catalog_pid"]').on('change', function () {
                var id = $(this).val();
                if (typeof _this.catalogs[id].child !== 'undefined') {
                    $('select[name="catalog_id"]').html('');
                    $('select[name="catalog_id"]').append('<option value="">请选择</option>');
                    $.each(_this.catalogs[id].child, function () {
                        $('select[name="catalog_id"]').append('<option value="' + this.id + '">' + this.name + '</option>');
                    });
                }
                $('.tax').hide();
            });
            $('select[name="catalog_id"]').on('change', function () {
                var pid = $('[name = "catalog_pid"]').val();
                var id = $(this).val();
                if (typeof _this.catalogs[pid].child !== 'undefined') {
                    var child = _this.catalogs[pid].child;
                    console.log(child);
                    var tax_info = {};
                    if (typeof child[id] !== 'undefined') {
                        tax_info = {
                            'import_tax': child[id].import_tax,
                            'consumption_tax': child[id].consumption_tax,
                            'value_added_tax': child[id].value_added_tax
                        };
                    }
                    if (tax_info) {
                        $('[name=import_tax]').val(tax_info.import_tax);
                        $('[name=consumption_tax]').val(tax_info.consumption_tax);
                        $('[name=value_added_tax]').val(tax_info.value_added_tax);
                        $('.tax').show();
                    }
                }
            });
            //选择分类
            $('#btn-cate').on('click', function (e) {
                e.preventDefault();
                _this.selectCate(e);
            });

            // 上传图片
            $('body').on('click', '.sku-image', function(e) {
                e.preventDefault();
                var that = $(this);
                var uploadDialog = dialog({
                    content: template('upload-tpl2', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame2")[0].contentWindow.image.get();
                        var $input = that.find('input');
                        that.find('img').attr('src', img.fileUrl);
                        $input.val(img.id);
                        _this.change($input);
                        $input.trigger('change');
                        //处理图片的左右点击替换事件的move函数
                        function move() {
                            $(".album-list li").find('a.up').show();
                            $(".album-list li").find("a.down").show();
                            $(".album-list li:eq(0)").find("a.up").hide();
                            $(".album-list li:last").find("a.down").hide();

                        }

                        //// 处理图片的左右点击替换事件
                        //move();
                        //$(".up").off().on("click", function (e) {
                        //    e.stopPropagation();
                        //    $(this).parents("li").insertBefore($(this).parents("li").prev());
                        //    move();
                        //    return false;
                        //});
                        //$(".down").off().on("click", function (e) {
                        //    e.stopPropagation();
                        //    $(this).parents("li").insertAfter($(this).parents("li").next());
                        //    move();
                        //    return false;
                        //});
                        //$("#album-view li").mouseover(function () {
                        //    $(".showmove").show();
                        //});
                        //$("#album-view li").mouseout(function () {
                        //    $(".showmove").hide();
                        //});
                    }, cancel: function () {
                    }
                });
                uploadDialog.show();

            });


            //包邮与商品重量的联动
            $('#free').on('click', function () {
                $('#weight').hide();
            });
            $('#not').on('click', function () {
                $('#weight').show();
            });
            $('[name=_byself]').on('click', function () {
                var valTmp = $(this).val();
                if(valTmp==1){
                    $('.free-shipping-div').hide();
                }else{
                    $('.free-shipping-div').show();
                }
            });
            //店铺分成模式的联动
            $('.user-defined').on('click', function () {
                $('.rebate-range').show();
                $('[name="rebate"]').val(20);
            })
            $('.site-defined').on('click', function () {
                $('.rebate-range').hide();
                $('[name="rebate"]').val(-1);
                //alert($('[name="rebate"]').val());
            })
            //分类删除
            $('body').on('click', '#cate-name a', function (e) {
                e.preventDefault();
                $(this).parent().remove();
                var cids = new Array();
                $('#cate-name').children().each(function () {
                    cids.push($(this).attr('id'));
                })
                //处理删除分类时不需要两人拼团价的分类
                $.ajax({
                    url: _global.url.api + 'not_group_two_cate',
                    data: {cate_ids: cids},
                    type: 'put',
                    success: function (res) {
                        if (res == 1) {
                            $('.group-two').css({'display': 'none'});
                            //alert($('.group-two').css('display'));
                        } else {
                            $('.group-two').css({'display': 'block'});
                            //alert($('.group-two').css('display'));
                        }
                    }
                });

                $.ajax({
                    url: _global.url.api + 'remove_specification',
                    data: {cid: cids, isGroup: false},
                    type: 'post',
                    dataType: 'json',
                    async: false,
                    success: function (res) {
                        if (res.code == 0) {
                            var sids = eval(res.data);
                            var sidsArr = new Array();
                            for (var i in sids) {
                                sidsArr[i] = 'spec' + sids[i];
                            }
                            var sidsLabel = new Array();
                            $('#myspecification').children('label').each(function () {
                                var re = $.inArray($(this).attr('id'), sidsArr);
                                if (re < 0) {
                                    $(this).next('br').remove();
                                    $(this).remove();
                                }
                            })
                        }
                    }
                });

                _this.model.data.cate_ids.remove($(this).parent().attr('id'));
            });

            //上传图片
            $('body').on('click', '#btn-upload', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });

            //上传视频
            $('body').on('click', '#btn-upload-video', function (e) {
                e.preventDefault();
                _this.upload_dialog = dialog({
                    content: template('upload-video-tpl', {}),
                    width: 550,
                    ok: function () {
                        var video = $("#upload-frame1")[0].contentWindow.video.get();
                        _this.videoPreview(video);
                        console.log(video);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
            $("body").on("click", '.video-remove', function (e) {
                e.preventDefault();
                $(this).parent('li').remove();
            });

            //选择sku
            $('#btn-select-sku').on('click', function (e) {
                _this.selectSku(e);
            });

            //添加sku
            $('#btn-add-sku').on('click', function (e) {
                e.preventDefault();
                if (typeof _this.attrs === 'undefined' || _this.attrs.length == 0) {
                    Alert({msg: '请先选择属性', type: 'error'});
                    return false;
                }
                $(".goods_unicoin").hide();
                _this.goodsSku.add({}, _this.attrs);

                if (!$('[name="is_free_tax"]').is(':checked')) {
                    $(".sku_tax_money").hide();
                }
            });

            //编辑器
            $('[name="details"]').ckeditor();
            $('#intro').ckeditor({toolbar: []});
        },
        change: function (e) {
            this.model.data[$(e.target).attr('name')] = $(e.target).val();
        },

        getChild: function (id) {
            if (typeof id === 'object') id = id[0];
            var child = [];
            for (var n in this.category) {
                if (id == this.category[n].id) {
                    child = this.category[n].child;
                    break;
                }
            }
            return child;
        },
        imgPreview: function (img) {
            var _this = this;
            $.each(img, function (n, v) {
                if (typeof v.id !== 'undefined') {
                    _this.album.add($(template('img-tpl', v)));
                }
            });
        },
        videoPreview: function (video) {
            var _this = this;
            console.log(video.id);
            if (typeof video.id !== 'undefined') {
                $('#video-view').html(template('video-tpl', video));
            }
        },

        //选择分类
        selectCate: function (e) {
            var _this = this;
            if (typeof _this.model.data.cate_ids == 'undefined') {
                _this.model.data.cate_ids = [];
            }
            //一级分类
            _this.cate_form = $(template('cate-tpl', {}));
            $.each(_this.category, function (n, v) {
                _this.cate_form.find('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
            });
            //显示二级分类，并联动
            //bind change event
            _this.cate_form.find('[name="cate"]').on('change', function () {
                _this.cate_form.find('[name="child-cate"]').html('');
                var child = _this.getChild($(this).val());
                $.each(child, function (n, v) {
                    _this.cate_form.find('[name="child-cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                });
            });
            //显示弹框
            _this.dialog = dialog({
                content: _this.cate_form,
                width: 400,
                ok: function () {
                    var temp = _this.cate_form.find('select[name="child-cate"]')[0].selectedOptions;
                    //alert(temp[0].value);
                    $.each(_this.cate_form.find('select[name="child-cate"]')[0].selectedOptions, function (n, option) {
                        if (_this.model.data.cate_ids.indexOf(option.value) >= 0) {
                            return false;
                        }
                        var el_cate = $('<span class="label label-info mr10" id="' + option.value + '">' + option.text +
                        ' <a href="" style="color: #fff"><span class="glyphicon glyphicon-remove"></span></a></span>');
                        $('#cate-name').append(el_cate);
                        _this.model.data.cate_ids.push(option.value);

                        //根据分类输出规格
                        $.ajax({
                            url: _global.url.api + 'get_specification',
                            data: {id: option.value, isGroup: false},
                            type: 'get',
                            async: false,
                            success: function (res) {
                                if (res.code == 0) {
                                    var item = res.data.mySpec;
                                    var spec_key = [];
                                    $.each(item, function () {
                                        //在选择多个分类时对规格去重
                                        var exist = document.getElementById('spec' + this.specification_id);
                                        if (exist) {
                                            return true;
                                        }
                                        //存储规格相关数据供提交数据时验证
                                        var spec = new Array();
                                        spec['name'] = this.sid;
                                        spec['required'] = this.is_required;
                                        spec['title'] = this.title;
                                        _this.spec_key.push(spec);
                                        //输出规格到页面
                                        var htm = '';
                                        if (this.is_required == '1') {
                                            htm += '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + '<span class="color_red">*</span>:<input type="text" name="' + this.sid + '" class="form-control" value=""></label><br>';
                                        } else {
                                            htm += '<label class="form-inline" id="spec' + this.specification_id + '">' + this.title + ':<input type="text" name="' + this.sid + '" class="form-control" value=""></label><br>';
                                        }
                                        $('#myspecification').append(htm);
                                    });
                                }
                            }
                        });
                    });
                    //处理点击添加分类时不需要两人拼团价的分类
                    var cate_ids = new Array();
                    $('#cate-name').children().each(function () {
                        cate_ids.push($(this).attr('id'));
                    });
                    $.ajax({
                        url: _global.url.api + 'not_group_two_cate',
                        data: {cate_ids: cate_ids},
                        type: 'put',
                        success: function (res) {
                            if (res == 1) {
                                $('.group-two').css({'display': 'none'});
                                //alert($('.group-two').css('display'));
                            } else {
                                $('.group-two').css({'display': 'block'});
                                //alert($('.group-two').css('display'));
                            }
                        }
                    });
                    _this.cate_form.remove();
                }, cancel: function () {
                }
            }).show(e.target);
        },

        //相册dom集合
        albumInit: function () {
            var that = this;
            this.album = {
                default: {
                    init: function () {
                        $('#album-view').append(this.el);
                        this.event();
                    },
                    event: function () {
                        var _this = this;
                        this.el.on('click', '.album-remove', function (e) {
                            _this.del(e);
                        }).on('click', '.album-default', function (e) {
                            _this.setDefault(e);
                        });
                    },
                    del: function (e) {
                        e.preventDefault();
                        this.el.remove();
                        that.model.set_data('album', that.album.get());
                    },
                    setDefault: function (e) {
                        e.preventDefault();
                        this.el.addClass('default').siblings().removeClass('default');
                        that.model.set_data('album', that.album.get());
                    }
                },
                images: [],
                add: function (el) {
                    this.images.push($.extend({el: el}, this.default));
                    this.images[this.images.length - 1].init();
                    that.model.set_data('album', this.get());
                },
                get: function () {
                    var images = [];
                    $.each($('[name="album"]'), function () {
                        var image = $(this).val();
                        //主图排前面
                        if ($(this).parent().hasClass('default')) {
                            images.unshift(image);
                        } else {
                            images.push(image);
                        }
                    });
                    return images;
                }
            }
        },

        //选择sku
        selectSku: function (e) {
            e.preventDefault();
            var _this = this;
            var cate_ids = new Array();
            $('#cate-name').children().each(function () {
                cate_ids.push($(this).attr('id'));
            });
            $.ajax({
                url: _global.url.api + 'not_group_two_cate',
                data: {cate_ids: cate_ids},
                type: 'put',
                success: function (res) {
                    if (res == 1) {
                        _this.skuAttrsTpl();
                    } else {
                        var group_price = $("#group_price").val();
                        $.ajax({
                            url: _global.url.api + 'site_group_discount',
                            data: {site_id: _global.site_info.id},
                            type: 'get',
                            success: function (res) {
                                if (res <= 0 && (group_price < 0 || typeof(group_price) != "number")) {
                                    dialog({
                                        title: '请设置2人拼团价',
                                        content: template('group-two-tpl'),
                                        width: 500,
                                        ok: function () {
                                            var data = {};
                                            data.group_price = $('#group-price-tpl').val();
                                            data.group_discount = $('#group-discount-tpl').val();
                                            data.goods_id = 0;
                                            console.log(data);
                                            if (new Model({
                                                    url: _global.url.api + 'group_two',
                                                    data: data
                                                }).put()) {
                                            }
                                            var group_price = parseFloat(data.group_price);
                                            $("#group_price").val(group_price.toFixed(2));
                                            _this.skuAttrsTpl();

                                        }, cancel: function () {
                                        }
                                    }).show();
                                } else {
                                    _this.skuAttrsTpl();
                                }
                            }
                        });
                    }
                }
            });
        },
        //商品属性
        skuAttrsTpl: function () {
            var _this = this;
            var el = $(template('sku-attrs-tpl', {goods_attrs: this.goods_attrs}));
            dialog({
                content: el,
                width: 400,
                ok: function () {
                    if (el.find('[name="goods_attr"]:checked').length > 2) {
                        Alert({msg: '商品属性最多只能选择两个', type: 'error'});
                        return false
                    }
                    $('#sku-attrs').html(''); //请空容器
                    //重置所有属性checked值
                    $.each(_this.goods_attrs, function () {
                        this.checked = false;
                    });
                    var attrs = [];
                    $.each(el.find('[name="goods_attr"]:checked'), function () {
                        var id = $(this).val();
                        $('#sku-attrs').append('<label class="label label-info">' + _this.goods_attrs[id].name + '</label> ');
                        _this.goods_attrs[id].checked = true;
                        attrs.push(_this.goods_attrs[id]);
                    });
                    el.remove();
                    _this.set('attrs', attrs);
                    _this.goodsSku.reset(attrs);
                    if (attrs.length == 0) {
                        $(".goods_unicoin").show();
                    }
                }, cancel: function () {
                }
            }).show();
        },

        //获取当前所选属性
        getAttrId: function () {
            var ids = [];
            if (typeof this.attrs === 'undefined') {
                return [];
            }
            $.each(this.attrs, function () {
                ids.push(this.id);
            });
            return ids;
        },

        //规格参数处理
        getSpecification: function () {

            var key = this.spec_key;

            for (var i = 0; i < key.length; i++) {
                key[i]['value'] = $('input[name="' + key[i]['name'] + '"]').val();
            }
            return key;
        },
        //sku对象
        goodsSkuInit: function () {
            var that = this;
            this.goodsSku = {
                default: {
                    template: 'goods-sku-tpl',
                    deleted: false, //是否已删除
                    init: function () {
                        this.el = $('<li class="list-group-item"></li>');
                        this.el.html(template(this.template, {attrs: this.attrs, sku: this.data}));
                        $('#goods-sku-view').append(this.el);
                        this.event();
                    },
                    event: function () {
                        var _this = this;
                        this.el.find('a').off().on('click', function (e) {
                            e.preventDefault();
                            _this.remove();
                        });
                        this.el.find('input,select').off().on('change', function (e) {
                            e.preventDefault();
                            _this.change(e);
                        });
                        //添加2人团购价
                        $('[name="sku_price"]').on('blur', function () {
                            var sku_this = this;
                            var sku_price = $(sku_this).val();
                            $.ajax({
                                url: _global.url.api + 'site_group_discount',
                                data: {site_id: _global.site_info.id},
                                type: 'get',
                                dataType: 'json',
                                success: function (res) {
                                    if (res > 0) {
                                        var sku_group_price = ((1 - res) * sku_price).toFixed(2);
                                        var objTmp = $(sku_this).parent().parent().find('[name="sku_group_price"]');
                                        objTmp.val(sku_group_price).change();
                                    } else {
                                        var sku_group_price = (0.99 * sku_price).toFixed(2);
                                        var objTmp = $(sku_this).parent().parent().find('[name="sku_group_price"]');
                                        objTmp.val(sku_group_price).change();
                                    }
                                }
                            });
                        });
                    },
                    change: function (e) {
                        var _this = this;
                        var val = $(e.target).val();
                        console.log(val);
                        if ($(e.target).attr('name') == 'attr_stock') {
                            console.log('change', $(e.target).attr('name'), typeof(val));
                            if (typeof(val) !== 'number' || val < 0) {
                                $(e.target).addClass('has-error');
                                Alert({msg: '库存格式错误', type: 'error'});
                                return false;
                            }
                        }

                        if ($(e.target).attr('name') == 'attr_values') {
                            _this.changeAttrValues();
                        } else {
                            var key = $(e.target).attr('name');
                            //移除name前缀attr_(解决干扰price等字段验证)
                            key = key.replace(/sku_/, "");
                            this.data[key] = val;
                        }
                        that.model.set_data('goods_sku', that.goodsSku.get());
                    },
                    changeAttrValues: function () {
                        var _this = this;
                        _this.data.goods_attr_values = [];
                        var values = _this.el.find('[name="attr_values"]');
                        $.each(_this.attrs, function (n, v) {
                            _this.data.goods_attr_values.push({
                                id: this.id,
                                name: this.name,
                                value: $(values[n]).val()
                            });
                        });
                    },
                    remove: function () {
                        this.el.remove();
                        this.deleted = true;
                        that.model.set_data('goods_sku', that.goodsSku.get());
                    }
                },
                collection: [],
                add: function (sku, attrs) {
                    var _coll = $.extend({data: sku, attrs: attrs}, this.default);
                    _coll.init();
                    this.collection.push(_coll);
                },
                get: function () {
                    var goodsSku = [];
                    $.each(this.collection, function () {
                        if (!this.deleted) {
                            goodsSku.push(this.data);
                        }
                    });
                    return goodsSku;
                },
                reset: function (attrs) {
                    $.each(this.collection, function () {
                        this.attrs = attrs;
                        this.el.html(template(this.template, {attrs: this.attrs, sku: this.data}));
                        this.changeAttrValues();
                        this.event();
                    });
                    that.model.set_data('goods_sku', this.get());
                },
                //验证属性填写是否完整
                validation: function () {
                    var _this = this;
                    var valid = true;
                    if (this.collection.length > 0) {
                        for (var i = 0; i < _this.collection.length; i++) {
                            var cl = _this.collection[i];

                            if (cl.deleted == true || cl.data.status == 2) continue;

                            //if (cl.deleted === false) {
                                //sn
                                /*if(!cl.data.sn) {
                                 _this.error('属性编码不能为空');
                                 valid = false;
                                 break;
                                 }*/
                                console.log(typeof cl.data.price);
                                if (cl.data.price != 0 && !parseInt(cl.data.price) && !parseFloat(cl.data.price)) {
                                    _this.error('属性价格填写不正确');
                                    valid = false;
                                    break;
                                }
                                if (isNaN(parseInt(cl.data.stock)) || cl.data.stock < 0) {
                                    _this.error('属性库存填写不正确');
                                    valid = false;
                                    break;
                                }
                            //}

                            var attrCl = cl.data.goods_attr_values;
                            if (_this.collection.length > 1) {
                                for (var t = i+1; t < _this.collection.length; t++) {

                                    var currentCl = _this.collection[t];
                                    if (currentCl.deleted == true || currentCl.data.status == 2) continue;

                                    var nextAttrCl = _this.collection[t].data.goods_attr_values;
                                    var nextRowV = '', rowV = '';
                                    if (attrCl) {
                                        for (var vi = 0; vi < attrCl.length; vi++) {
                                            nextRowV = nextRowV + nextAttrCl[vi].value;
                                            rowV = rowV + attrCl[vi].value;
                                        }
                                        if (rowV == nextRowV) return false;
                                    }
                                }
                            }

                        }
                    }
                    return valid;
                },
                error: function (msg) {
                    Alert({msg: msg, typ: 'error'});
                }
            }
        }

    };

    new index();

});